<template>
  <div class="page-container">
    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="e => selection = e">
    </ex_super_table_page>
    <ex_super_dialog_form ref="formDialog" v-bind="dialog" @afterSubmitSuccess="reload()">
    </ex_super_dialog_form>
    <ex_super_dialog_form ref="printWallDialog" v-bind="printWallDialog" noSubmit>
    </ex_super_dialog_form>
    <print_common_temp ref="print_common_wall" businessType="DISTRIBUTE_WALL" :tableModel="[
      { key: 'wallCode', label: 'label_distribution_wall_code', 'min-width': 120, 'show-overflow-tooltip': true, },
      { key: 'quantity', label: 'label_grid_mouth_count', 'min-width': 120, 'show-overflow-tooltip': true, },
    ]" :metaHandler="(data, row) => {
  return {
    wallCode: row.wallCode,
    wallContainerCode: '',
  }
}" />
    <print_common_temp ref="print_common_wall_box" businessType="DISTRIBUTE_WALL" :tableModel="[
      { key: 'wallCode', label: 'label_distribution_wall', 'min-width': 120, 'show-overflow-tooltip': true, },
      { key: 'containerCode', label: 'label_grid_mouth_code', 'min-width': 120, 'show-overflow-tooltip': true, },
    ]" :metaHandler="(data, row) => {
  return {
    wallCode: row.wallCode,
    wallContainerCode: row.containerCode,
  }
}" />
  </div>
</template>
<script>
import print_common_temp from '@/component/print/print_common_temp'

import superTablePageFunction from '@/mixin/super-table-page-function';
export default {
  title: 'label_distribution_wall_manage',
  mixins: [superTablePageFunction],
  components: { print_common_temp },
  data() {
    return {
      selection: [],

      option: {
        search: {
          model: [
            { label: "label_distribution_wall_code", key: "wallCode", },
            {
              label: "label_status", key: "status", type: 'select', enum: 'IsAvailableStatusEnum',
            },
          ],
        },
        action: [
          {
            label: 'label_new_distribution_wall', auth: 'wms_distribution_wall_edit', attrs: { icon: "el-icon-plus" }, click: () => {
              this['$refs']['formDialog'].showNew({
                title: this.$tt('label_new_distribution_wall'),
                data: {},
                onlySetData: true,
              })
            }
          },
        ],
        actionExtra: [
          {
            label: { _key: 'label_print_any', i18n: true, type: "label_distribution_wall" }, attrs: { type: "primary" }, click: (row) => {
              if (_.isEmpty(this.selection)) {
                return this.$message.error(this.$tt('tip_please_select_order'))
              }
              this.$refs.print_common_wall.show(this.selection)
            }
          },
        ],
        table: {
          url: "/wms-api/outbound/OutboundDistributionWallRpc/selectPage.json",
          attrs: {},
          model: [
            { type: 'selection', clickToggle: true, keyGroup: 'label_table_operate' },

            { key: 'wallCode', label: 'label_code', 'min-width': 120, 'show-overflow-tooltip': true, },
            {
              key: 'wallType', label: 'label_type', 'width': 140, 'show-overflow-tooltip': true,
              formatter: (r, c, v, i) => this.$enumShow(v, "WmsDistributionWallTypeEnum")
            },
            {
              key: 'areaCodes', label: 'label_warehouse_area_code', 'width': 140, 'show-overflow-tooltip': true,
            },
            { key: 'quantity', label: 'label_grid_mouth_count', 'min-width': 120, 'show-overflow-tooltip': true, },
            { key: 'status', label: 'label_status', 'min-width': 120, formatter: (r, c, v, i) => this.$enumShow(v, "IsAvailableStatusEnum") },

            { key: 'rowCount', label: 'label_row_count', 'min-width': 120, },
            { key: 'colCount', label: 'label_col_count', 'min-width': 120, },

            { key: 'gmtCreate', label: 'label_create_time', 'width': 130, 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$dateFormat(v) },
            { key: 'gmtModify', label: 'label_modify_time', 'width': 130, 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$dateFormat(v) },

            {
              type: 'operate', width: 210, fixed: "right", operate: [
                {
                  label: 'label_edit', auth: 'wms_distribution_wall_edit', click: (row) => {
                    this['$refs']['formDialog'].showNew({
                      title: this.$formatNameCode(this.$tt('label_edit_distribution_wall'), row.wallCode),
                      params: { "id": row["id"] },
                    })
                  }
                },
                {
                  label: 'label_start_using', auth: 'wms_distribution_wall_disable',
                  if: (row) => row.status == "DISABLED",
                  type: "confirm-button", url: '/wms-api/outbound/OutboundDistributionWallRpc/updateWallStatus.json', message: 'label_fms_bank_card_confirm_delete',
                  buttonClass: "button_text_success", confirmButtonType: 'success',
                  params: (row) => { return { "wallId": row["id"], status: 'ENABLE' } }, done: ['reload', 'tip']
                },
                {
                  label: 'label_stop_using', auth: 'wms_distribution_wall_disable',
                  if: (row) => row.status == "ENABLE",
                  type: "confirm-button", url: '/wms-api/outbound/OutboundDistributionWallRpc/updateWallStatus.json', message: 'label_fms_bank_card_confirm_delete',
                  buttonClass: "button_text_danger", confirmButtonType: 'danger',
                  params: (row) => { return { "wallId": row["id"], status: 'DISABLED' } }, done: ['reload', 'tip']
                },
                {
                  label: 'label_delete', auth: 'wms_distribution_wall_delete', type: "confirm-button", url: '/wms-api/outbound/OutboundDistributionWallRpc/remove.json', message: 'label_fms_bank_card_confirm_delete',
                  buttonClass: "button_text_danger", confirmButtonType: 'danger',
                  params: (row) => { return { "id": row["id"] } }, done: ['reload', 'tip']
                },
                {
                  type: 'more',
                  items: [
                    { label: { _key: 'label_print_any', i18n: true, type: "label_distribution_wall" }, click: (row) => this.$refs.print_common_wall.show([row]) },
                    {
                      label: { _key: 'label_print_any', i18n: true, type: "label_grid_mouth" }, click: (row) => this.$refs.printWallDialog.showNew({
                        title: this.$formatNameCode(this.$tt({ _key: 'label_print_any', i18n: true, type: "label_grid_mouth" }), row.wallCode),
                        params: { "id": row["id"] },
                      })
                    },

                  ]
                },
              ]
            },
          ],
          // operate: [
          // ],
        },
      },
      printWallDialog: {
        customClass: 'dialog_extra',
        detailUrl: '/wms-api/outbound/OutboundDistributionWallRpc/detail.json',
        detailDataHandle: (data) => {
          data.containerList.forEach(it => it.wallCode = data.wallCode)
          return data
        },
        form: {
          default: {},
          model: [
            {
              key: 'wallCode', label: 'label_sortwall_code', disabled: (data) => !_.isEmpty(data.id),
            },
            {
              key: '', label: '',
              render: (h, { data }) => {
                return (<el-button onClick={e => {
                  const select = this.$refs.printWallDialog.getRef("containerList").getSelection()
                  this.$refs.print_common_wall_box.show(_.isEmpty(select) ? data.containerList : select)
                }}>{this.$t('label_print_select_record')}</el-button>)
              }
            },
            {
              key: 'containerList', label: 'label_grid_mouth', formType: "itemTable",
              attrs: {

              },
              model: [
                { type: 'selection', clickToggle: true, keyGroup: 'label_table_operate' },
                { key: 'containerCode', label: "label_sortwall_grid_mouth", 'min-width': 130, 'show-overflow-tooltip': true, },
                {
                  type: 'operate', width: 210, operate: [
                    {
                      label: { _key: 'label_print_any', i18n: true, type: "label_grid_mouth" }, click: (row) => {
                        this.$refs.print_common_wall_box.show([row])
                      }
                    },
                  ]
                },
              ],
            },

          ],

        }
      },
      dialog: {
        customClass: 'dialog_extra',
        submitUrl: '/wms-api/outbound/OutboundDistributionWallRpc/saveUpdate.json',
        submitDataHandle: (data) => {
          if (["PARTITION"].includes(data.wallType)) {
            data.areaCodes = data.areaCodes ? data.areaCodes.join(",") : ""
          } else {
            data.areaCodes = ""
          }
          data.quantity = data.containerList.length
          data.containerList.forEach(it => {
            if (data.id) it.wallId = data.id

            it.wallCode = data.wallCode
            it.containerLength = data.containerLength
            it.containerWidth = data.containerWidth
            it.containerHeight = data.containerHeight
          })
          return data
        },
        detailUrl: '/wms-api/outbound/OutboundDistributionWallRpc/detail.json',
        detailDataHandle: (data) => {
          data.areaCodes = data.areaCodes ? data.areaCodes.split(",") : []
          this.refreshContainerList(data)
          return data
        },
        form: {
          itemClass: "form_item_mini", inputClass: "form_input_small",
          formClass: " flex_row_wrap ",
          default: { wallCode: '', quantity: 0, rowCount: 0, colCount: 0, containerList: [] },

          model: [
            { header: "label_base_info", },
            {
              key: 'wallCode', label: 'label_code', disabled: (data) => !_.isEmpty(data.id),
              render: (h, { data }) => (

                <ex_super_input disabled={!_.isEmpty(data.id)} value={data.wallCode}
                  onInput={e => {
                    this.$set(data, "wallCode", e.trim())
                    this.refreshContainerName(data)
                  }}
                />

              )
            },
            {
              key: 'wallType', label: 'label_type', type: "select", enum: "WmsDistributionWallTypeEnum"
            },
            {
              key: 'assignUserIds', label: 'label_assign_user', type: "common_user_select", multiple:true,
            },
            {
              key: 'areaCodes', label: 'label_warehouse_area_code', if: (data) => ["PARTITION"].includes(data.wallType),
              // renderItem: (h, { data }) => {
              //   return (<el-form-item class="form_item_mini" label={this.$tt("label_warehouse_area_code")}>
              //     <base_area_select class="form_input_small"
              //       value={data.areaCodes} multiple={true}
              //       option={{ label: 'labelStr', value: 'code' }}
              //       onInput={e => this.$set(data, 'areaCodes', e)}
              //     />
              //   </el-form-item>)
              // },
              type: 'base_area_select',
              attrs: {
                option: { label: 'labelStr', value: 'code' },
                multiple: true,
              },
            },
            { key: 'length', label: 'label_length', },
            { key: 'width', label: 'label_width', },
            { key: 'height', label: 'label_height', },

            { key: 'containerLength', label: 'label_grid_mouth_length', },
            { key: 'containerWidth', label: 'label_grid_mouth_width', },
            { key: 'containerHeight', label: 'label_grid_mouth_height', },

            { key: 'quantity', label: 'label_grid_mouth_count', disabled: true },

            {
              key: 'rowCount', label: 'label_row_count',
              render: (h, { data }) => {
                return h('el-input-number', {
                  class: "form_input_small",
                  props: {
                    disabled: !_.isEmpty(data.id),
                    value: data.rowCount,
                    "step-strictly": true,
                    min: 0, max: 10,
                  },
                  on: {
                    input: (e) => {
                      this.$set(data, 'rowCount', e)
                      this.refreshContainerList(data)
                    }
                  }
                })
              }
            },
            {
              key: 'colCount', label: 'label_col_count',
              render: (h, { data }) => {
                return h('el-input-number', {
                  class: "form_input_small",
                  props: {
                    disabled: !_.isEmpty(data.id),
                    value: data.colCount,
                    "step-strictly": true,
                    min: 0, max: 10,
                  },
                  on: {
                    input: (e) => {
                      this.$set(data, 'colCount', e)
                      this.refreshContainerList(data)
                    }
                  }
                })
              }
            },

            {
              key: 'containerList', label: 'label_grid_mouth', itemStyle: 'width:100%', itemClass: "",
              render: (h, { data }) => {
                if (_.isEmpty(data.containerList)) return this.$tt("tip_no_data")

                let child = []
                for (let y = 1; y <= data.rowCount; y++) {
                  let innerChild = []
                  for (let x = 1; x <= data.colCount; x++) {
                    const item = this.findContainer(data, x, y)
                    const i = (x - 1) + (y - 1) * data.colCount + 1
                    if (item) {
                      innerChild.push(
                        h('div', {
                          key: x + "/" + y,
                          style: "width:100px;min-width:100px;justify-content: space-between;",
                          key: "containerCode_" + i,
                          class: {
                            "mg_1": true,
                            bold: true,
                            "flex_col_center": true,
                            tag_warning: item.useFlag == "Y",
                            tag_success: item.useFlag != "Y" && item.status == "ENABLE",
                            tag_danger: item.useFlag != "Y" && item.status != "ENABLE",
                          },
                        }, [
                          item.focus == true ?
                            (<el-input class="flex_cell el-input-nopadding" ref={"containerCode_" + i}
                              value={item.containerCode}
                              onInput={e => this.$set(item, 'containerCode', e)}
                              onBlur={e => this.$set(item, 'focus', false)} />) :
                            (<div class="flex_cell " onClick={e => {
                              {/* data.containerList.forEach(c => {
                                this.$set(c, 'focus', false)
                              })
                              this.$set(item, 'focus', true)
                              this.$nextTick(() => {
                                const inputC = this.$refs.formDialog.$refs.form.$refs["containerCode_" + i]
                                if (inputC) {
                                  inputC.focus()
                                }
                              }) */}
                            }} style="white-space: normal;">{item.containerCode}</div>),
                          (<el-button size="mini"
                            style="padding: 5px 10px;font-size: 12px;margin-top:5px;"
                            type={item.useFlag == "Y" ? 'warning' : item.status == "ENABLE" ? 'success' : 'danger'}
                            disabled={item.useFlag == "Y"}
                            round
                            onClick={e => { this.$set(item, "status", item.status != "ENABLE" ? 'ENABLE' : "DISABLED") }}
                          >{this.$tt(item.useFlag == "Y" ? 'label_use_ing' : item.status == "ENABLE" ? 'label_enable_int' : 'label_disable_ing')}</el-button>),

                        ])
                      )
                    } else {
                      innerChild.push(
                        h('div', {
                          key: x + "/" + y,
                          class: "mg_1 tag_info",
                        }, "EMPTY")
                      )
                    }
                  }
                  child.push(
                    h('div', {
                      style: 'line-height:14px',
                      class: "flex_row",
                    }, innerChild)
                  )

                }

                if (data.rowCount && data.colCount) {
                  return h("div", {
                    class: 'form_input_extra',
                    style: 'overflow: auto;max-height:300px;width:100%'
                  }, child)
                }


              }
            },

          ],
          rules: {
            wallCode: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            wallType: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            areaCodes: { required: true, type: 'array', message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            rowCount: [
              { type: 'number', required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
              { type: 'number', min: 1, message: this.$tt('tip_no_less_any', { type: 1 }), trigger: 'blur' },
              { type: 'number', max: 10, message: this.$tt('tip_no_more_any', { type: 10 }), trigger: 'blur' },
            ],
            colCount: [
              { type: 'number', required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
              { type: 'number', min: 1, message: this.$tt('tip_no_less_any', { type: 1 }), trigger: 'blur' },
              { type: 'number', max: 10, message: this.$tt('tip_no_more_any', { type: 10 }), trigger: 'blur' },
            ],
            containerList: { type: 'array', required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          },
        }
      },
    };
  },
  methods: {

    findContainer(data, x, y) {

      return _.find(data.containerList, it => it.rowIndex == y && it.columnIndex == x)
    },
    closeContainer(data, x, y) {
      const i = _.findIndex(data.containerList, it => it.rowIndex == y && it.columnIndex == x)
      if (i >= 0) {
        data.containerList.splice(i, 1)
      }
    },
    refreshContainerName(data) {
      data.containerList.forEach((it, i) => {
        let i_code = (it.columnIndex - 1) + (it.rowIndex - 1) * data.colCount + 1
        i_code = _.padStart(i_code, 3, '0');

        this.$set(it, 'containerCode', `${data.wallCode}_${i_code}`)
      })
    },
    refreshContainerList(data) {

      if (!data.containerList) data.containerList = []
      const out = data.containerList
        .filter(it => it.rowIndex <= data.rowCount && it.columnIndex <= data.colCount)
      for (let y = 1; y <= data.rowCount; y++) {
        for (let x = 1; x <= data.colCount; x++) {
          const i = (x - 1) + (y - 1) * data.colCount + 1
          let item = _.find(out, it => it.rowIndex == y && it.columnIndex == x)
          if (item == null) {
            item = {
              focus: false,
              status: "ENABLE",
              useFlag: "N",
              rowIndex: y,
              columnIndex: x,
            }
            out.push(item)
          }
        }
      }
      data.quantity = data.containerList.length
      data.containerList = out
      this.refreshContainerName(data)
    },

  }
};

</script>
<style></style>
